package com.papercutting.platform.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.papercutting.platform.dto.query.CultureQuery;
import com.papercutting.platform.dto.request.CultureRequest;
import com.papercutting.platform.dto.response.CultureResponse;
import com.papercutting.platform.dto.response.PageResult;
import com.papercutting.platform.entity.Culture;
import com.papercutting.platform.entity.UserLike;
import com.papercutting.platform.mapper.CultureMapper;
import com.papercutting.platform.service.CultureService;
import com.papercutting.platform.service.UserLikeService;
import com.papercutting.platform.service.UserFavoriteService;
import com.papercutting.platform.util.EntityConverter;
import com.papercutting.platform.util.ImageUrlUtil;
import com.papercutting.platform.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 剪纸文化服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CultureServiceImpl implements CultureService {

    private final CultureMapper cultureMapper;
    private final UserLikeService userLikeService;
    private final UserFavoriteService userFavoriteService;
    private final JwtUtil jwtUtil;
    private final ImageUrlUtil imageUrlUtil;
    
    @Override
    @Transactional
    public Long createCulture(CultureRequest request) {
        log.info("创建文化内容: {}", request.getTitle());

        Culture culture = EntityConverter.toCulture(request);
        culture.setCreateTime(LocalDateTime.now());
        culture.setUpdateTime(LocalDateTime.now());
        culture.setDeleted(false);

        // 设置默认值
        if (culture.getViewCount() == null) culture.setViewCount(0);
        if (culture.getLikeCount() == null) culture.setLikeCount(0);
        if (culture.getFavoriteCount() == null) culture.setFavoriteCount(0);
        if (culture.getShareCount() == null) culture.setShareCount(0);
        if (culture.getSortOrder() == null) culture.setSortOrder(0);
        if (culture.getIsRecommend() == null) culture.setIsRecommend(false);
        if (culture.getIsTop() == null) culture.setIsTop(false);

        cultureMapper.insert(culture);

        log.info("文化内容创建成功，ID: {}", culture.getId());
        return culture.getId();
    }

    @Override
    @Transactional
    public void updateCulture(CultureRequest request) {
        log.info("更新文化内容: {}", request.getId());

        Culture existingCulture = cultureMapper.selectById(request.getId());
        if (existingCulture == null || existingCulture.getDeleted()) {
            throw new RuntimeException("文化内容不存在");
        }

        EntityConverter.updateCulture(existingCulture, request);
        existingCulture.setUpdateTime(LocalDateTime.now());

        cultureMapper.updateById(existingCulture);

        log.info("文化内容更新成功，ID: {}", request.getId());
    }

    @Override
    @Transactional
    public void deleteCulture(Long id) {
        log.info("删除文化内容: {}", id);

        // 检查文化内容是否存在
        Culture culture = cultureMapper.selectById(id);
        if (culture == null) {
            throw new RuntimeException("文化内容不存在");
        }

        // 使用 MyBatis Plus 的逻辑删除
        cultureMapper.deleteById(id);

        log.info("文化内容删除成功，ID: {}", id);
    }

    @Override
    @Transactional
    public void batchDeleteCultures(List<Long> ids) {
        log.info("批量删除文化内容: {}", ids);
        
        if (ids == null || ids.isEmpty()) {
            throw new RuntimeException("删除ID列表不能为空");
        }
        
        // 检查所有文化内容是否存在
        List<Culture> cultures = cultureMapper.selectBatchIds(ids);
        if (cultures.size() != ids.size()) {
            List<Long> existingIds = cultures.stream().map(Culture::getId).collect(Collectors.toList());
            List<Long> missingIds = ids.stream().filter(id -> !existingIds.contains(id)).collect(Collectors.toList());
            log.warn("部分文化内容不存在: {}", missingIds);
        }
        
        // 使用 MyBatis Plus 的批量逻辑删除
        if (!cultures.isEmpty()) {
            List<Long> existingIds = cultures.stream().map(Culture::getId).collect(Collectors.toList());
            cultureMapper.deleteBatchIds(existingIds);
        }
        
        log.info("批量删除文化内容成功，实际删除数量: {}", cultures.size());
    }

    @Override
    public CultureResponse getCultureById(Long id) {
        log.info("获取文化内容详情: {}", id);

        Culture culture = cultureMapper.selectById(id);
        if (culture == null || culture.getDeleted()) {
            throw new RuntimeException("文化内容不存在");
        }

        CultureResponse response = EntityConverter.toCultureResponse(culture);
        // 处理图片URL
        if (response.getCoverImage() != null) {
            response.setCoverImage(imageUrlUtil.processImageUrl(response.getCoverImage()));
        }
        
        return response;
    }
    
    @Override
    public PageResult<CultureResponse> getCulturePage(CultureQuery query) {
        log.info("分页查询文化列表: {}", query);

        Page<Culture> page = new Page<>(query.getPage(), query.getSize());
        IPage<Culture> result = cultureMapper.selectCulturePage(page, query);

        List<CultureResponse> responseList = result.getRecords().stream()
                .map(culture -> {
                    CultureResponse response = EntityConverter.toCultureResponse(culture);
                    // 处理图片URL
                    if (response.getCoverImage() != null) {
                        response.setCoverImage(imageUrlUtil.processImageUrl(response.getCoverImage()));
                    }
                    return response;
                })
                .collect(Collectors.toList());

        return PageResult.of(responseList, result.getTotal(), query.getPage(), query.getSize());
    }

    @Override
    public List<CultureResponse> getCultureList(CultureQuery query) {
        log.info("获取文化列表: {}", query);

        List<Culture> cultures = cultureMapper.selectCultureList(query);
        return cultures.stream()
                .map(EntityConverter::toCultureResponse)
                .collect(Collectors.toList());
    }

    @Override
    public List<CultureResponse> getRecommendedCultures(Integer limit) {
        log.info("获取推荐文化列表，限制数量: {}", limit);

        List<Culture> cultures = cultureMapper.selectRecommendedCultures(limit);
        return cultures.stream()
                .map(culture -> {
                    CultureResponse response = EntityConverter.toCultureResponse(culture);
                    // 处理图片URL
                    if (response.getCoverImage() != null) {
                        response.setCoverImage(imageUrlUtil.processImageUrl(response.getCoverImage()));
                    }
                    return response;
                })
                .collect(Collectors.toList());
    }

    @Override
    public List<CultureResponse> getTopCultures() {
        log.info("获取置顶文化列表");

        List<Culture> cultures = cultureMapper.selectTopCultures();
        return cultures.stream()
                .map(culture -> {
                    CultureResponse response = EntityConverter.toCultureResponse(culture);
                    // 处理图片URL
                    if (response.getCoverImage() != null) {
                        response.setCoverImage(imageUrlUtil.processImageUrl(response.getCoverImage()));
                    }
                    return response;
                })
                .collect(Collectors.toList());
    }
    
    @Override
    @Transactional
    public void increaseViewCount(Long id) {
        log.info("增加浏览量: {}", id);

        int updated = cultureMapper.increaseViewCount(id);
        if (updated == 0) {
            log.warn("增加浏览量失败，文化内容不存在或已删除: {}", id);
        }
    }

    @Override
    @Transactional
    public Map<String, Object> likeCulture(String token, Long cultureId) {
        log.info("点赞操作开始: cultureId={}, token={}...", cultureId, token != null ? token.substring(0, Math.min(20, token.length())) : "null");

        // 从token获取用户ID
        Long userId = getUserIdFromToken(token);
        log.info("从token解析得到的userId: {}", userId);
        
        if (userId == null) {
            log.error("无法从token解析用户ID，token可能无效或过期");
            throw new RuntimeException("用户未登录");
        }

        Culture culture = cultureMapper.selectById(cultureId);
        if (culture == null || culture.getDeleted()) {
            throw new RuntimeException("文化内容不存在");
        }

        // 获取操作前的状态
        boolean wasLiked = userLikeService.findByUserIdAndTargetTypeAndTargetId(
            userId, "culture", cultureId) != null;
        
        // 执行幂等的点赞切换操作
        boolean isNowLiked = userLikeService.toggleLike(userId, "culture", cultureId);
        
        // 根据状态变化更新点赞数（避免并发时的数据不一致）
        if (isNowLiked && !wasLiked) {
            // 从未点赞变为已点赞
            cultureMapper.increaseLikeCount(cultureId);
        } else if (!isNowLiked && wasLiked) {
            // 从已点赞变为未点赞
            cultureMapper.decreaseLikeCount(cultureId);
        }
        // 如果状态没有变化（isNowLiked == wasLiked），则不更新计数

        // 重新查询最新的点赞数，确保数据准确性
        Culture updatedCulture = cultureMapper.selectById(cultureId);
        int currentLikeCount = updatedCulture != null ? updatedCulture.getLikeCount() : culture.getLikeCount();

        Map<String, Object> result = new HashMap<>();
        result.put("isLiked", isNowLiked);
        result.put("liked", isNowLiked);  // 兼容前端两种字段名
        result.put("likeCount", currentLikeCount);
        
        log.info("点赞操作完成: userId={}, cultureId={}, wasLiked={}, isNowLiked={}, likeCount={}", 
                 userId, cultureId, wasLiked, isNowLiked, currentLikeCount);
        
        return result;
    }

    @Override
    @Transactional
    public Map<String, Object> unlikeCulture(String token, Long cultureId) {
        log.info("取消点赞操作开始: cultureId={}", cultureId);

        // 从token获取用户ID
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            throw new RuntimeException("用户未登录");
        }

        Culture culture = cultureMapper.selectById(cultureId);
        if (culture == null || culture.getDeleted()) {
            throw new RuntimeException("文化内容不存在");
        }

        // 检查是否已点赞
        boolean wasLiked = userLikeService.findByUserIdAndTargetTypeAndTargetId(
            userId, "culture", cultureId) != null;
        
        if (!wasLiked) {
            // 如果没有点赞，直接返回未点赞状态
            Map<String, Object> result = new HashMap<>();
            result.put("isLiked", false);
            result.put("liked", false);
            result.put("likeCount", culture.getLikeCount());
            log.info("用户未点赞，直接返回: {}", result);
            return result;
        }

        // 强制取消点赞（不使用toggle，直接删除）
        try {
            // 查找并删除点赞记录
            UserLike existingLike = userLikeService.findByUserIdAndTargetTypeAndTargetId(
                userId, "culture", cultureId);
            
            if (existingLike != null) {
                userLikeService.deleteById(existingLike.getId());
                log.info("强制删除点赞记录: ID={}", existingLike.getId());
            }
            
            // 减少点赞数
            cultureMapper.decreaseLikeCount(cultureId);
            
            // 重新查询最新的点赞数
            Culture updatedCulture = cultureMapper.selectById(cultureId);
            int currentLikeCount = updatedCulture != null ? updatedCulture.getLikeCount() : 
                                   Math.max(culture.getLikeCount() - 1, 0);

            Map<String, Object> result = new HashMap<>();
            result.put("isLiked", false);
            result.put("liked", false);
            result.put("likeCount", currentLikeCount);
            
            log.info("取消点赞完成: userId={}, cultureId={}, likeCount={}", 
                     userId, cultureId, currentLikeCount);
            
            return result;
            
        } catch (Exception e) {
            log.error("取消点赞失败: ", e);
            throw new RuntimeException("取消点赞失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Map<String, Object> favoriteCulture(String token, Long cultureId) {
        log.info("收藏操作: {}", cultureId);

        // 从token获取用户ID
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            throw new RuntimeException("用户未登录");
        }

        Culture culture = cultureMapper.selectById(cultureId);
        if (culture == null || culture.getDeleted()) {
            throw new RuntimeException("文化内容不存在");
        }

        // 检查当前收藏状态（只查询有效的收藏记录）
        boolean isCurrentlyFavorited = userFavoriteService.findByUserIdAndTargetTypeAndTargetId(
            userId, "culture", cultureId) != null;
        
        log.info("收藏操作前状态 - 用户ID: {}, 文化ID: {}, 当前是否已收藏: {}", userId, cultureId, isCurrentlyFavorited);
        
        // 切换收藏状态
        boolean newFavoritedStatus = userFavoriteService.toggleFavorite(userId, "culture", cultureId);
        
        log.info("收藏操作后状态 - 新收藏状态: {}", newFavoritedStatus);
        
        // 更新文化内容的收藏数
        // 只有在状态真正发生变化时才更新计数
        if (newFavoritedStatus != isCurrentlyFavorited) {
            if (newFavoritedStatus) {
                // 从未收藏变为已收藏：增加计数
                log.info("增加收藏计数，文化ID: {}", cultureId);
                cultureMapper.increaseFavoriteCount(cultureId);
                culture.setFavoriteCount(culture.getFavoriteCount() + 1);
            } else {
                // 从已收藏变为未收藏：减少计数
                log.info("减少收藏计数，文化ID: {}", cultureId);
                cultureMapper.decreaseFavoriteCount(cultureId);
                culture.setFavoriteCount(Math.max(culture.getFavoriteCount() - 1, 0));
            }
        } else {
            log.info("收藏状态未发生变化，不更新计数");
        }

        Map<String, Object> result = new HashMap<>();
        result.put("isFavorited", newFavoritedStatus);
        result.put("favorited", newFavoritedStatus);  // 兼容前端两种字段名
        result.put("favoriteCount", culture.getFavoriteCount());
        return result;
    }
    
    @Override
    public PageResult<CultureResponse> searchCulture(String keyword, CultureQuery query) {
        log.info("搜索文化内容: {}", keyword);

        // 设置搜索关键词到查询条件中 - 修正为keyword字段
        if (StringUtils.hasText(keyword)) {
            query.setKeyword(keyword);
        }

        return getCulturePage(query);
    }

    @Override
    public List<Map<String, Object>> getCategoryStats() {
        log.info("获取分类统计");

        // TODO: 实现获取分类统计逻辑，需要在Mapper中添加相应方法
        List<Map<String, Object>> stats = new ArrayList<>();

        // 临时返回示例数据
        for (int i = 1; i <= 4; i++) {
            Map<String, Object> stat = new HashMap<>();
            stat.put("category", i);
            stat.put("count", 0);
            stats.add(stat);
        }

        return stats;
    }

    @Override
    @Transactional
    public void batchUpdateStatus(List<Long> ids, Integer status) {
        log.info("批量更新状态: {} -> {}", ids, status);

        if (ids == null || ids.isEmpty()) {
            return;
        }

        // TODO: 在Mapper中添加批量更新方法
        for (Long id : ids) {
            Culture culture = cultureMapper.selectById(id);
            if (culture != null && !culture.getDeleted()) {
                culture.setStatus(status);
                culture.setUpdateTime(LocalDateTime.now());
                cultureMapper.updateById(culture);
            }
        }
    }

    @Override
    public List<Culture> findAll() {
        log.info("获取所有文化内容");

        CultureQuery query = new CultureQuery();
        return cultureMapper.selectCultureList(query).stream()
                .map(culture -> {
                    Culture entity = new Culture();
                    BeanUtils.copyProperties(culture, entity);
                    return entity;
                })
                .collect(Collectors.toList());
    }
    
    @Override
    @Transactional
    public void increaseShareCount(Long id) {
        log.info("增加分享量: {}", id);
        cultureMapper.increaseShareCount(id);
    }
    
    @Override
    public List<CultureResponse> getRelatedCultures(Long id, Integer category, Integer limit) {
        log.info("获取相关文化内容: id={}, category={}, limit={}", id, category, limit);
        
        CultureQuery query = new CultureQuery();
        query.setCategory(category);
        query.setStatus(1); // 只获取已发布的内容
        
        List<Culture> cultures = cultureMapper.selectCultureList(query);
        
        // 排除当前文章，并限制数量
        return cultures.stream()
                .filter(culture -> !culture.getId().equals(id))
                .limit(limit != null ? limit : 5)
                .map(EntityConverter::toCultureResponse)
                .collect(Collectors.toList());
    }
    
    @Override
    public Map<String, Object> checkUserInteractionStatus(String token, Long cultureId) {
        log.info("检查用户交互状态: {}", cultureId);
        
        Long userId = getUserIdFromToken(token);
        Map<String, Object> result = new HashMap<>();
        
        if (userId != null) {
            boolean isLiked = userLikeService.findByUserIdAndTargetTypeAndTargetId(
                userId, "culture", cultureId) != null;
            boolean isFavorited = userFavoriteService.findByUserIdAndTargetTypeAndTargetId(
                userId, "culture", cultureId) != null;
            
            result.put("isLiked", isLiked);
            result.put("isFavorited", isFavorited);
        } else {
            result.put("isLiked", false);
            result.put("isFavorited", false);
        }
        
        return result;
    }
    
    @Override
    @Transactional
    public void recordView(Long id) {
        log.info("记录浏览: {}", id);
        increaseViewCount(id);
    }
    
    /**
     * 从JWT token中获取用户ID
     */
    private Long getUserIdFromToken(String token) {
        try {
            log.info("开始解析token: {}...", token != null ? token.substring(0, Math.min(20, token.length())) : "null");
            
            if (token == null || token.trim().isEmpty()) {
                log.warn("token为空");
                return null;
            }
            
            // 移除Bearer前缀（如果存在）
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
                log.info("移除Bearer前缀后的token: {}...", token.substring(0, Math.min(20, token.length())));
            }
            
            // 解析JWT token获取用户ID
            Object userId = jwtUtil.getUserIdFromToken(token);
            log.info("JWT工具类返回的userId: {} (类型: {})", userId, userId != null ? userId.getClass().getSimpleName() : "null");
            
            if (userId instanceof Long) {
                return (Long) userId;
            } else if (userId instanceof String) {
                Long parsedId = Long.parseLong((String) userId);
                log.info("字符串userId转换为Long: {}", parsedId);
                return parsedId;
            }
            
            log.warn("userId类型不匹配或为null");
            return null;
        } catch (Exception e) {
            log.error("从token解析用户ID失败: {}", e.getMessage(), e);
            return null;
        }
    }
}